import { z } from "zod";
import { ConfigReader } from "../utils/config-reader.js";

export const initConfigSchema = z.object({
  // No parameters needed for init
});

export type InitConfigArgs = z.infer<typeof initConfigSchema>;

export async function initConfigTool(
  args: InitConfigArgs
): Promise<string> {
  try {
    const configReader = new ConfigReader(process.cwd());
    
    // Check if config already exists
    const configExists = await configReader.configExists();
    
    if (configExists) {
      return `📁 Configuration directory already exists at \`.codebase-rag/\`

**Existing Configuration:**
- Use \`.codebase-rag/.include-dirs\` to specify directories to include
- Use \`.codebase-rag/.exclude-dirs\` to specify directories to exclude

**Tips:**
- One pattern per line
- Use glob patterns (e.g., \`src/\`, \`**/*.ts\`)
- Lines starting with # are comments
- Empty lines are ignored`;
    }

    // Create example configuration files
    await configReader.createExampleConfigs();
    
    return `✅ **Configuration Initialized**

**Created:**
- \`.codebase-rag/.include-dirs\` - Define directories to include in indexing
- \`.codebase-rag/.exclude-dirs\` - Define directories to exclude from indexing

**Configuration Format:**
- One pattern per line
- Use glob patterns like those in .gitignore
- Lines starting with # are comments
- Empty lines are ignored

**Examples:**
Include patterns:
\`\`\`
src/
docs/
*.md
**/*.ts
\`\`\`

Exclude patterns:
\`\`\`
node_modules/
dist/
*.log
**/*.test.js
\`\`\`

**Next Steps:**
1. Edit the configuration files to match your project structure
2. Run \`index <directory>\` to index with your custom patterns`;
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    return `❌ Failed to initialize configuration: ${errorMessage}

**Possible Issues:**
- Permission denied for creating directories
- Disk space issues
- File system access errors

Please check your permissions and try again.`;
  }
}